#include "stdafx.h"
#include "ActionManager.h"
#include "Actions.h"


CActionManager::CActionManager()
{
	BindAction(eKey_Tilde, actions::toggle_console);
}

CActionManager::~CActionManager()
{
	assert(m_listeners.empty());
}

void CActionManager::RegisterListener(IActionListener* listener)
{
	stl::push_back_unique(m_listeners, listener);
}

void CActionManager::UnregisterListener(IActionListener* listener)
{
	stl::find_and_remove(m_listeners, listener);
}

void CActionManager::OnInputEvent(const SInputEvent& input_event)
{
	if (input_event.key_state == eKeyState_Pressed && !input_event.autorepeat)
	{
		static const SActionEvent INVALID_ACTION_EVENT("");
		const SActionEvent& action_event = stl::find_in_map(m_binds, input_event.event_type, INVALID_ACTION_EVENT);
		if (action_event != INVALID_ACTION_EVENT)
			NotifyAction(action_event);
	}
}

void CActionManager::BindAction(EInputEvent input_event, const SActionEvent& action)
{
	m_binds.insert(std::make_pair(input_event, action));
}

void CActionManager::NotifyAction(const SActionEvent& action_event)
{
	for (TListeners::iterator it = m_listeners.begin(); it != m_listeners.end(); ++it)
	{
		IActionListener* listener = *it;
		listener->OnActionEvent(action_event);
	}
}